package com.li.shirospringboot.config;

import com.li.shirospringboot.pojo.Player;
import com.li.shirospringboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义UserRealm      extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService service;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了>授权");

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermission("player:add");

        Subject subject= SecurityUtils.getSubject();
        Player player = (Player) subject.getPrincipal();

        info.addStringPermission(player.getScore());


        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了>认证");
        //用户名、密码


        UsernamePasswordToken token1 = (UsernamePasswordToken) token;
        Player player=service.QueryByName(token1.getUsername());


        if(player==null){//没有这个人
            return null;  //抛出异常
        }

        //密码认证，shiro做
        return new SimpleAuthenticationInfo(player,player.getPassword(),"");
    }
}
